package com.wanggsx.library.base.views.pagerscroller;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

/**
 * Created by wanggsx on 15/12/9.
 */
public class HorizontalPagerScroller0 extends HorizontalScrollView {

    private Context mContext;
    public LinearLayout mContainer;
    //上一个
    private View viewPre = null;
    //当前
    private View viewThis = null;
    //下一个
    private View viewAfter = null;
    //下一次用于上场的view
    private View viewForth = null;
    //临时view，用于交换暂存
    private View viewTmp = null;
    private ScrollListener0 mListener;

    private int MOVE_SMALL_DISTANCE = 40;

    public HorizontalPagerScroller0(Context context) {
        super(context);
    }

    public HorizontalPagerScroller0(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setHorizontalScrollBarEnabled(false);
    }

    /**
     * 初始化容器的尺寸及位置
     *
     * @param width        宽度
     * @param height       高度
     * @param marginLeft   左边距
     * @param marginTop    上边距
     * @param marginRight  右边距
     * @param marginBottom 底边距
     */
    public void initScrollerLocation(int width, int height, int marginLeft, int marginTop, int marginRight, int marginBottom, ScrollListener0 l) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
        params.setMargins(marginLeft, marginTop, marginRight, marginBottom);
        setLayoutParams(params);
        mListener = l;
    }

    /**
     * 设置监听事件，用于绑定数据
     *
     * @param l
     */
    public void setListener(ScrollListener0 l) {
        mListener = l;
    }


    /**
     * 设置页数
     *
     * @param num         总页数
     * @param layoutId    布局文件id
     * @param width       页宽
     * @param height      页高
     * @param marginLeft  页的左外边距(最后一个页的右外边距同左，其余右边距为0)
     * @param paddingLeft 容器的左内边距(右内边距同左)
     */
    public void initPagerLocation(int num, int layoutId, int width, int height, int marginLeft, int paddingLeft) {
        Log.d("wan", "wanggsx 初始化pager");
        removeView(mContainer);
        removeAllViews();
        mContainer = new LinearLayout(mContext);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mContainer.setLayoutParams(params);
        addView(mContainer);
        mContainer.setPadding(paddingLeft, 0, paddingLeft, 0);
        totalPage = num;
        currentPageIndex = 0;
        originX = 0;
        scrollerPaddingLeftOrRight = paddingLeft;
        pagerLayoutId = layoutId;
        pagerWidth = width;
        pagerHeight = height;
        pagerMarginLeft = marginLeft;
        //从一个pager到另一个pager的实际距离
        pagerTotalWith = width + marginLeft;
        currentPageIndex = 0;
        if (totalPage >= 4) {
            for (int i = currentPageIndex; i <= currentPageIndex + 2; i++) {
                View child = getViewFromLayout(null, i);
                mContainer.addView(child);
            }
            viewPre = mContainer.getChildAt(0);
            viewThis = mContainer.getChildAt(1);
            viewAfter = mContainer.getChildAt(2);
        } else if (totalPage >= 1) {
            for (int i = 0; i < totalPage; i++) {
                View child = getViewFromLayout(null, i);
                mContainer.addView(child);
            }
        }
    }

    private int pagerLayoutId, pagerWidth, pagerHeight;

    private View getViewFromLayout(View view, int position) {
        View child = view;
        if (view == null) {
            child = LayoutInflater.from(mContext).inflate(pagerLayoutId, null);
        }
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pagerWidth, pagerHeight);
        params.setMargins(pagerMarginLeft, 0, (totalPage == position + 1) ? pagerMarginLeft : 0, 0);
        child.setLayoutParams(params);
        child.setTag(position);
        mListener.setViewData(position, child);
        return child;
    }

    public void setPageSize(int pageSize) {
        totalPage = pageSize;
    }

    private int totalPage, currentPageIndex, nextPageIndex, pagerTotalWith, scrollerPaddingLeftOrRight, pagerMarginLeft;
    private float startMoveX, scrollDistance, originX;
    private boolean tfIsFirstMove = true;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startMoveX = ev.getX();
                tfIsFirstMove = false;
                break;
            case MotionEvent.ACTION_UP:
                int oldIndex = currentPageIndex;
                scrollDistance = ev.getX() - startMoveX;
                if (scrollDistance > 0) {
                    //向右滑
                    if (scrollDistance > MOVE_SMALL_DISTANCE) {
                        if (currentPageIndex == 0) {
                            nextPageIndex = currentPageIndex;
                        } else if (currentPageIndex == 1 || currentPageIndex == totalPage - 1) {
                            nextPageIndex = --currentPageIndex;
                            mListener.onScrollToFront(nextPageIndex);
                        } else {
                            nextPageIndex = --currentPageIndex;
                            mListener.onScrollToFront(nextPageIndex);
                            viewTmp = viewAfter;
                            mContainer.addView(getViewFromLayout(viewForth, nextPageIndex - 1), 0);
                        }
                    } else {
                        nextPageIndex = currentPageIndex;
                    }
                } else {
                    //向左滑
                    if (scrollDistance < -MOVE_SMALL_DISTANCE) {
                        if (currentPageIndex == totalPage - 1) {
                            nextPageIndex = currentPageIndex;
                        } else if (currentPageIndex == totalPage - 2 || currentPageIndex == 0) {
                            nextPageIndex = ++currentPageIndex;
                            mListener.onScrollToNext(nextPageIndex);
                        } else {
                            nextPageIndex = ++currentPageIndex;
                            mListener.onScrollToNext(nextPageIndex);
                            viewTmp = viewPre;
                            mContainer.addView(getViewFromLayout(viewForth, nextPageIndex + 1));
                        }
                    } else {
                        nextPageIndex = currentPageIndex;
                    }
                }
                originX = pagerTotalWith * nextPageIndex;
                smoothScrollTo((int) originX, 0);
                int intpaddingleft = scrollerPaddingLeftOrRight + pagerTotalWith * (nextPageIndex - 1);
                tfIsFirstMove = true;
                if (oldIndex > nextPageIndex && nextPageIndex >= 1 && nextPageIndex < totalPage - 1 - 1) {
                    //向右滑了
                    viewAfter = viewThis;
                    viewThis = viewPre;
                    viewPre = viewForth;
                    viewForth = viewTmp;
                    mContainer.removeView(viewForth);
                    while (mContainer.getChildCount() >= 4) {
                        mContainer.removeViewAt(0);
                    }
                    mContainer.setPadding(intpaddingleft, 0, scrollerPaddingLeftOrRight, 0);
                    int xx = mContainer.getWidth() - 2 * 1087 - mContainer.getPaddingLeft() - 45;
                    Log.d("wan", "wanggsx 右滑 xx:" + xx + " scrollTo:" + originX + " mContainer.getPaddingLeft:" + mContainer.getPaddingLeft() + " mContainer.getWidth():" + mContainer.getWidth() + " mContainer.getChildCount:" + mContainer.getChildCount() + " mContainer.getPaddingRight:" + mContainer.getPaddingRight());
                } else if (oldIndex < nextPageIndex && nextPageIndex >= 2 && nextPageIndex <= totalPage - 1 - 1) {
                    //向左滑了
                    viewPre = viewThis;
                    viewThis = viewAfter;
                    viewAfter = viewForth;
                    viewForth = viewTmp;
                    mContainer.removeView(viewForth);
                    while (mContainer.getChildCount() >= 4) {
                        mContainer.removeViewAt(mContainer.getChildCount() - 1);
                    }
                    mContainer.setPadding(intpaddingleft, 0, scrollerPaddingLeftOrRight, 0);
                    if (currentPageIndex == totalPage - 2) {
                        getViewFromLayout(mContainer.getChildAt(mContainer.getChildCount() - 1), totalPage - 1);
                    }
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            smoothScrollBy(pagerMarginLeft, 0);
                        }
                    }, 160);
                    int xx = mContainer.getWidth() - 2 * 1087 - mContainer.getPaddingLeft() - 45;
                    Log.d("wan", "wanggsx 左滑 xx:" + xx + " scrollTo:" + originX + " mContainer.getPaddingLeft:" + mContainer.getPaddingLeft() + " mContainer.getWidth():" + mContainer.getWidth() + " mContainer.getChildCount:" + mContainer.getChildCount() + " mContainer.getPaddingRight:" + mContainer.getPaddingRight());
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (tfIsFirstMove) {
                    startMoveX = ev.getX();
                    tfIsFirstMove = false;
                }
                float scrollDistance = ev.getX() - startMoveX;
                scrollTo((int) (originX - scrollDistance), 0);
                break;
            case MotionEvent.ACTION_CANCEL:
                originX = pagerTotalWith * currentPageIndex;
                smoothScrollTo((int) originX, 0);
                tfIsFirstMove = true;
                break;
        }
        return true;
    }

}
